<?php
set_time_limit(300);
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 资源分类管理
 */
class source_type extends admin
{

    private $db;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('source_type_model');
        $this->siteid = get_siteid();
    }

    /**
     * 分类列表
     */
    public function index()
    {
        $type = $_GET['type']?(int) $_GET['type']:1;
        if ($type == 1) {
            $model_type = pc_base::load_model('news_nsr_model');
        } else if ($type == 2) {
            $model_type = pc_base::load_model('video_nsr_model');
        } else if ($type == 3) {
            $model_type = pc_base::load_model('picture_nsr_model');
        }
        $where = ' siteid = ' . $this->siteid .' AND status <> 2 AND type = ' . $type;

        $tree = pc_base::load_sys_class('tree');
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        //读取数据
        $result = $this->db->select($where);
        $show_detail = count($result) < 500 ? 1 : 0;
        $parentid = $_GET['parentid'] ? intval($_GET['parentid']) : 0;
        $html_root = pc_base::load_config('system','html_root');
        $types = array(0 => L('category_type_system'),1 => L('category_type_page'),2 => L('category_type_link'));
        if(!empty($result)) {
            foreach($result as $r) {
                $r['str_manage'] = '';
                $type_id = array();
                $type_id[] = $r['id'];
                if ($r['parentid'] > 0) {
                    $type_id = implode('\',\'', $type_id);
                    $where =" type_id in ('$type_id')";
                } else {
                    $typearray = $this->db->select(array('parentid'=>$r['id']));
                    if (!empty($typearray)) {
                        foreach ($typearray as $v) {
                            $type_id[] = $v['id'];
                        }
                    }
                    $type_id = implode('\',\'', $type_id);
                    $where =" type_id in ('$type_id')";
                }
                $r['num'] = $model_type->count($where);
                if(!$show_detail) {
                    if($r['parentid']!=$parentid) continue;
                    $r['parentid'] = 0;
                    $r['str_manage'] .= '<a href="?m=picture&c=source_type&a=index&type='.$type.'&parentid='.$r['id'].'&pc_hash='.$_SESSION['pc_hash'].'">['.L('manage_sub_category').']</a> ';
                }
                if ($r['parentid'] == 0) {
                    $r['str_manage'] .= '<a href="javascript:;" onclick="edit1('.$r['id'].', \''.new_addslashes(new_html_special_chars($r['cn_name'])).'\')" title="'.L('add_sub_category').'">'.L('add_sub_category').'</a> | ';
                }
                $r['str_manage'] .= '<a href="javascript:;" onclick="edit('.$r['id'].', \''.new_addslashes(new_html_special_chars($r['cn_name'])).'\')" title="'.L('edit').'">'.L('edit').' | </a> ';
                $r['str_manage'] .= '<a href="javascript:confirmurl(\'?m=picture&c=source_type&a=delete&id='.$r['id'].'\',\''.L('confirm',array('message'=>addslashes($r['cn_name']))).'\')">'.L('delete').'</a> ';
                $r['status'] = $r['status'] == 0?'禁用':'可用';
                if(strlen($r['type_icon'])>0){$r['type_icon']='<img src="'.$r['type_icon'].'"  height="60" />';}else{$r['type_icon']="<span style='color:red;'>（未设置）</span>";}
                $r['display_icon'] = $r['parentid'] ? '' : ' <img src ="'.IMG_PATH.'icon/gear_disable.png" title="'.L('not_display_in_menu').'">';
                $categorys[$r['id']] = $r;
            }
        }

        $str  = "<tr>
                    <td align='center'>\$id</td>
                    <td align='left'>\$spacer\$cn_name\$display_icon</td>
                    <td align='center'>\$en_name</td>
                    <td align='center'>\$type_icon</td>
                    <td align='center'>\$num</td>
                    <td align='center'>\$create_time</td>
                    <td align='center'>\$status</td>
                    <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
        $big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=picture&c=source_type&a=add&type='.$type.'\', title:\''.L('add_source_type_'.$type).'\', width:\'700\', height:\'200\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_source_type_'.$type));
        include $this->admin_tpl('source_list');
    }

    /**
     * 添加分类
     */
    public function add()
    {
        $type = $_GET['type']?(int) $_GET['type']:1;
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $source = $this->check($_POST['source']);
            $titlepd = $this->public_check_type($source['en_name']);
            if (!$titlepd) {
                showmessage('英文标识已经存在', HTTP_REFERER);
            }
            $source['type'] = $type;
            $source['type_icon'] = $_POST['data']['type_icon'];
            $id = $this->db->insert($source, true);

            //记录行为日志
            $log_content = '添加分类[新生成分类id：'.$id.'，分类中文名：'.$source['cn_name'].']';
            $this->manage_admin_log($log_content);

            if ($id) {
                showmessage(L('add_source_success'), HTTP_REFERER, '', 'add');
            } else {
                showmessage(L('add_source_error'), HTTP_REFERER);
            }
        } else {
            $show_validator = $show_scroll = $show_header = true;
            $select_categorys = $this->db->getSource($type,$_GET['parentid'],1);
            pc_base::load_sys_class('form', '', 0);
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('source_add');
        }
    }

    /**
     * 分类修改
     */
    public function edit()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $source = $this->check($_POST['source'], 'edit');
            $source['type_icon'] = $_POST['data']['type_icon'];
            $titlepd = $this->public_check_type($source['en_name']);
            if (!$titlepd) {
                showmessage('英文标识已经存在', HTTP_REFERER);
            }
            $ids = $this->db->update($source, array('id' => $id,'siteid' => $this->siteid));

            //记录行为日志
            $log_content = '修改分类[分类id：'.$id.'，分类中文名：'.$source['cn_name'].']';
            $this->manage_admin_log($log_content);

            if ($ids) {
                showmessage(L('edit_source_success'), HTTP_REFERER, '', 'edit');
            } else {
                showmessage(L('edit_source_error'), HTTP_REFERER);
            }
        } else {
            $show_validator = $show_scroll = $show_header = true;
            pc_base::load_sys_class('form', '', 0);
            $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
            extract($info);
            $select_categorys = $this->db->getSource($type,$parentid,1);
            //获取站点模板信息
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('source_edit');
        }
    }

    /**
     * 分类删除
     */
    public function delete()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_parameters'), HTTP_REFERER);
        } else {
            $id = intval($_GET['id']);
            $list = $this->db->select(array('parentid'=>$id,'status'=>1,'siteid'=>$this->siteid));
            if ($list) {
                showmessage(L('cateid_zi_fenlei'), HTTP_REFERER);
            }
            if ($id < 1)
                return false;
            $result = $this->db->update(array('status'=>2), array('id' => $id,'siteid' => $this->siteid));

            //记录行为日志
            $log_content = '删除分类[分类id：'.$id.']';
            $this->manage_admin_log($log_content);

            if ($result) {
                showmessage(L('operation_success'), HTTP_REFERER);
            } else {
                showmessage(L("operation_failure"), HTTP_REFERER);
            }
        }
    }

    /**
     * 检验英文标识否存在，避免英文标识重复
     */
    public function public_check_type ($en_name)
    {
        if(!$en_name) showmessage('英文标识不能为空', HTTP_REFERER);;
        $en_name = addslashes($en_name);
        $type = (int) $_GET['type'];
        if($_GET['id']) {
            $id = intval($_GET['id']);
            $r = $this->db->get_one(array('id'=>$id, 'siteid' => $this->siteid));
            if($r['en_name'] == $en_name) {
                return true;
            }
        }
        $r = $this->db->get_one(array('siteid' => $this->siteid, 'en_name' => $en_name, 'type'=>$type), 'id');
        if($r['id']) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 表单验证
     * 
     * @param array $data
     *            表单传递的值
     * @param string $a
     *            add/edit添加操作时，自动加上默认值
     */
    private function check($data, $a = 'add')
    {
        if ($a == 'add') {
            $data['siteid'] = $this->siteid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['created_by'] = $_SESSION['userid'];
        } else {
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $_SESSION['userid'];
        }
        return $data;
    }
}